//
//  PPTimelineMessageObject.m
//  pickpic
//
//  Created by Jinxiao on 10/6/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPTimelineMessageObject.h"

@implementation PPTimelineMessageObject

+ (instancetype)messageForParameters:(NSDictionary *)parameters {
    PPTimelineMessageObject *message = [[PPTimelineMessageObject alloc] init];

    NSString *type = [parameters validStringForKey:@"type"];
    if([type isEqualToString:@"Follow"]) {
        message.type = PPTimelineMessageTypeFollow;
    } else if([type isEqualToString:@"Like"]) {
        message.type = PPTimelineMessageTypeLike;
    } else if([type isEqualToString:@"AddFavorite"]) {
        message.type = PPTimelineMessageTypeFavorite;
    } else if([type isEqualToString:@"Commented"]) {
        message.type = PPTimelineMessageTypeComment;
    } else if([type isEqualToString:@"Pickpic"]) {
        message.type = PPTimelineMessageTypePickpic;
    } else {
        message.type = PPTimelineMessageTypeUnknown;
    }

    message.date = [NSDate dateWithTimeIntervalSince1970:[parameters validNumberForKey:@"createDate"].doubleValue/1000.0];

    message.brief = [parameters validStringForKey:@"content"];

    NSDictionary *sourceUser = [parameters validDictionaryForKey:@"sourceUser"];
    if(sourceUser != nil) {
        PPTimelineUserObject *user = [PPTimelineUserObject userForParameters:sourceUser];
        message.user = user;
    }
    
    NSDictionary *sourceAlbum = [parameters validDictionaryForKey:@"sourceAlbum"];
    if(sourceAlbum != nil) {
        PPAlbumObject *album = [PPAlbumObject albumForParameters:sourceAlbum];
        message.album = album;
    }

    NSDictionary *sourcePicture = [parameters validDictionaryForKey:@"sourcePicture"];
    if(sourcePicture != nil) {
        PPTimelinePictureObject *picture = [PPTimelinePictureObject pictureForParameters:sourcePicture];
        message.picture = picture;
    }
    
    return message;
}

- (void)encodeWithCoder:(NSCoder *)encoder
{
    [encoder encodeInteger:self.type forKey:@"type"];
    [encoder encodeObject:self.comment forKey:@"comment"];
    [encoder encodeObject:self.date forKey:@"date"];
    [encoder encodeObject:self.brief forKey:@"brief"];
    [encoder encodeObject:self.user forKey:@"user"];
    [encoder encodeObject:self.album forKey:@"album"];
    [encoder encodeObject:self.picture forKey:@"picture"];
}

- (id)initWithCoder:(NSCoder *)decoder
{
    self = [super init];
    if (self) {
        self.type = [decoder decodeIntegerForKey:@"type"];
        self.comment = [decoder decodeObjectForKey:@"comment"];
        self.date = [decoder decodeObjectForKey:@"date"];
        self.brief = [decoder decodeObjectForKey:@"brief"];
        self.user = [decoder decodeObjectForKey:@"user"];
        self.album = [decoder decodeObjectForKey:@"album"];
        self.picture = [decoder decodeObjectForKey:@"picture"];
    }
    return self;
}

@end
